﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;

public class jshSplitTexture : MonoBehaviour {

    public Texture2D tex;
    public GameObject go;
    public int splitCount;
    public int u;
    public int v;

    private List<GameObject> allGO = new List<GameObject>();
    //private GameObject[] allGO;
    private int perTexSize;
    //private Texture2D newTex;

	// Use this for initialization
	void Start () {
        //设定提取出的每个Icon大小
        perTexSize = tex.width / splitCount;
        SplitTexture();
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void SplitTexture()
    {
        for (int i = 0; i < Mathf.Pow(splitCount,2); i++)
        {
            //提取分割图片
            Color[] getTexColor = tex.GetPixels(u * perTexSize, v * perTexSize, perTexSize, perTexSize);

            //创建新的纹理并设置图片到新的——Texture2D——上
            Texture2D newTex = new Texture2D(perTexSize, perTexSize);
            newTex.SetPixels(getTexColor);
            newTex.Apply();

            //创建新的GameObject并将Texture2D赋予
            GameObject initGO = Instantiate(go) as GameObject;
            allGO.Add(initGO);
            initGO.name = u.ToString() + v.ToString();
            initGO.renderer.material.mainTexture = newTex;

            if (u == splitCount - 1) {v++; u = 0;}
            else u++;
        }
        //StartCoroutine("RandomTheTex");
        RandomTheTex();
    }

    //删除最后一张图片并打乱图片位置
    void RandomTheTex()
    {
        allGO.Remove(allGO[allGO.Count - 1]);
        float x = 0f;
        float y = 0f;
        while (allGO.Count  != 0)
        {
            int a = Random.Range(0, allGO.Count);
            allGO[a].transform.position = new Vector3(x, y, 0f);
            if (x == splitCount - 1) { y--; x = 0; }
            else x++;
            allGO.Remove(allGO[a]);
            //yield return null;
        }
    }

    void OnGUI()
    {
        GUI.DrawTexture(new Rect(10, 30, tex.width/2, tex.height/2), tex, ScaleMode.ScaleToFit);
        GUI.Label(new Rect(10, 10, 100, 50), "参考图");
    }
}
